package com.salesmanager.core.business.product.service;

import com.salesmanager.core.business.generic.dao.SalesManagerEntityDao;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.service.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.product.Product;
import com.salesmanager.core.business.product.dao.ProductDao;
import com.salesmanager.core.business.statistics.model.ProductCriteria;
import com.salesmanager.core.modules.cms.common.CmsFileManager;
import com.salesmanager.core.modules.cms.common.CmsFileManagerFacade;
import com.salesmanager.web.model.paging.PaginationDataList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by LiuTong on 2017/11/21.
 */
@Service("productService")
public class ProductServiceImpl extends SalesManagerEntityServiceImpl<Long, Product> implements ProductService  {

    @Autowired
    private CmsFileManager cmsFileManager;


    private CmsFileManagerFacade facade = null;


    private CmsFileManagerFacade getCmsFileManagerFacade(){
        if (facade == null) facade = new CmsFileManagerFacade(cmsFileManager);
        return facade;
    }


    private ProductDao productDao;

    @Autowired
    public ProductServiceImpl(ProductDao productDao) {
        super(productDao);
        this.productDao = productDao;
    }

    @Override
    public PaginationDataList<Product> getProductList(ProductCriteria criteria) {
        return productDao.getProductList(criteria);
    }

    @Override
    public void saveOrUpdate(Product product) throws ServiceException {
        String oldImagName = null;
        if (product.getId()!=null){
            Product product1 = super.getById(product.getId());
            //oldFileName = product1.getImagName();
            oldImagName = product1.getImagName();
            super.update(product);
        }else {
            super.create(product);
        }

        if (product.getImagInputStream()!=null){
            this.getCmsFileManagerFacade().uploadAppImageFile(product.getProductCode(), product.getImagName(), product.getImagInputStream());

            //文件名相同会把新上传的文件删除
            if (oldImagName!=null && !oldImagName.equals(product.getImagName())){
                this.getCmsFileManagerFacade().removeAppImageFile(product.getProductCode(),oldImagName);
            }
        }
    }
}
